import axios from 'axios'
import { message } from 'antd'
import Cookies from 'js-cookie'

declare module 'axios' {
  interface AxiosInstance {
    (config: AxiosRequestConfig): Promise<any>
  }
}

const Message = message
const http = axios.create({
  baseURL: '/api',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
  },
})

// 请求拦截器
http.interceptors.request.use(
  (req: any) => {
    // token 添加，login 接口添加token
    const token = sessionStorage.getItem('token')
    if (token) {
      Object.assign(req.headers, { token })
    }
    return req
  },
  (error) => Promise.reject(error),
)

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    const { errorCode, data, message } = response.data
    // console.log(response, 'response')
    const errorMessage = message
    // 判断是否成功
    if (errorCode === '0000') {
      // 成功返回数据
      // Message.success(`获取数据成功.${JSON.stringify(data)}`)
      return data
    } else {
      Message.error(errorMessage)
      return Promise.reject(new Error(errorMessage))
    }
  },
  (error) => {
    Message.error(error)
    return Promise.reject(error)
  },
)

export default http
